/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-09 16:16:46
 * @LastEditTime: 2023-08-31 16:25:06
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { ChevronDownIcon } from '@chakra-ui/icons';
import {
  Avatar,
  Box,
  Button,
  Flex,
  Popover,
  PopoverContent,
  PopoverTrigger,
  Stack,
  useColorModeValue,
} from '@chakra-ui/react';
import { $authToken } from '@tourfly/api';

import { FC, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { MdLogout } from 'react-icons/md';
import {
  Link as ReactRouterLink,
  // useLocation,
  useNavigate,
} from 'react-router-dom';

import userService from '@/api/user.service';
import MyDivider from '@/common/components/Divider';
import { removeToken } from '@/common/utils';
import { getToken } from '@/common/utils';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { reset as resetProfile } from '@/store/profileSlice';
import { logout, setIsLogin, setUserInfo } from '@/store/user';

const UserMenu: FC = () => {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  // const { pathname } = useLocation();
  // const showMenus = pathname.indexOf('aigc') >= 0;
  const navigate = useNavigate();
  const { userInfo, isLogin } = useAppSelector((state) => state.user);
  // const popoverContentBgColor = useColorModeValue('white', 'gray.800');
  const handleLogout = () => {
    dispatch(logout());
    removeToken();
    $authToken.set(undefined);
    dispatch(resetProfile());
    navigate('/signin');
  };
  const bg = useColorModeValue('#000000', 'base.800');
  const h_bg = useColorModeValue('gray.900', 'base.750');
  const btn_bg = useColorModeValue('base.900', 'base.800');
  const btn_hover_bg = useColorModeValue('base.850', 'base.750');
  const popoverContent_bg = useColorModeValue('base.950', 'base.850');

  const sx = {
    bg: btn_bg,
    color: 'base.300',
    _hover: { bg: btn_hover_bg },
    variant: 'ghost',
    rounded: 'base',
  };

  useEffect(() => {
    /** 没有token的情况 */
    if (!isLogin && getToken()) {
      userService
        .getUserInfo()
        .then((res) => {
          if (!res.rt || !res.rt.token || !res.rt.userInfo) {
            removeToken();
            $authToken.set(undefined);
          } else {
            dispatch(setUserInfo(res.rt.userInfo));
            dispatch(setIsLogin(true));
          }
        })
        .catch(() => {
          removeToken();
          $authToken.set(undefined);
        });
    }
  }, [dispatch, isLogin]);
  if (isLogin) {
    return (
      <Popover trigger="hover" placement="bottom-start">
        <PopoverTrigger>
          <Box>
            <Button
              variant="ghost"
              color="#666666"
              _hover={{
                bg: 'base.900',
                color: '#333333',
              }}
              _dark={{
                color: 'base.500',
                _hover: {
                  color: 'base.200',
                },
              }}
              px={2}
              rounded="base"
              onClick={() => navigate('/gallery')}
              display={{ base: 'none', md: 'flex' }}
              rightIcon={<ChevronDownIcon />}
            >
              {userInfo.username}
            </Button>

            <Flex w="40px" justify="center">
              <Avatar
                shadow="md"
                display={{ base: 'flex', md: 'none' }}
                name={userInfo.username}
                size="sm"
                cursor="pointer"
                onClick={() => navigate('/gallery')}
              />
            </Flex>
          </Box>
        </PopoverTrigger>
        <PopoverContent
          bg={popoverContent_bg}
          p={4}
          borderRadius="base"
          w="150px"
        >
          <Stack>
            <Button sx={sx} as={ReactRouterLink} to="/gallery">
              个人中心
            </Button>

            {/* {showMenus && (
                <>
                  <Button as={ReactRouterLink} to="/training" sx={sx}>
                    {t('common.train')}
                  </Button>
                </>
              )} */}
            <MyDivider />
            <Button sx={sx} onClick={handleLogout} rightIcon={<MdLogout />}>
              {t('profile.logout')}
            </Button>
          </Stack>
        </PopoverContent>
      </Popover>
    );
  }
  return (
    <Stack
      flex={{ base: 1, md: 0 }}
      justify="flex-end"
      direction="row"
      spacing={0}
    >
      <Button
        px="2"
        as={ReactRouterLink}
        fontSize="sm"
        fontWeight={600}
        variant="link"
        cursor="pointer"
        color="#666666"
        _hover={{
          color: '#333333',
          textDecoration: 'underline',
        }}
        to="/signin"
      >
        {t('profile.login')}
      </Button>
      <Button
        as={ReactRouterLink}
        fontSize="sm"
        fontWeight={600}
        color="white"
        bg={bg}
        to="/registry"
        cursor="pointer"
        _hover={{
          bg: h_bg,
        }}
      >
        {t('profile.registry')}
      </Button>
    </Stack>
  );
};

export default UserMenu;
